package com.rms.recruit_management_system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rms.recruit_management_system.mapper.PositionsMapper;
import com.rms.recruit_management_system.mapper.ResumeMapper;
import com.rms.recruit_management_system.pojo.Positions;
import com.rms.recruit_management_system.pojo.Resume;
import com.rms.recruit_management_system.service.ResumeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ResumeServiceImpl extends ServiceImpl<ResumeMapper, Resume> implements ResumeService {

    @Autowired
    private ResumeMapper resumeMapper;
    @Autowired
    private PositionsMapper positionsMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String username;

    /**
     * 用户提交简历之后，这个职位的被投递数量+1
     * @param resume
     */
    @Override
    public void addResume(Resume resume) {
        resumeMapper.insert(resume);
        Positions positions=positionsMapper.selectOne(new QueryWrapper<Positions>().eq("position_name",resume.getIntention()));
        Positions positions1=new Positions();
        positions1.setSubmitQuantity(positions.getSubmitQuantity()+1);
        positionsMapper.update(positions1,new QueryWrapper<Positions>().eq("position_name",resume.getIntention()));
    }

    /**
     * 删除简历信息
     * @param id
     */
    @Override
    public void deleteResume(Integer id) {
        Resume resume=new Resume();
        resume.setIsFlag(1);
        LambdaQueryWrapper<Resume> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Resume::getId, id);
        resumeMapper.update(resume, wrapper);
    }

    /**
     * 分页查询简历信息
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    @Override
    public IPage<Resume> getResumeList(int pageNum, int pageSize,String search) {

        Page<Resume> page=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Resume> wrapper= Wrappers.<Resume>lambdaQuery();
        wrapper.ne(Resume::getIsFlag,1);
        if(StrUtil.isNotBlank(search)){
            wrapper.like(Resume::getEducation,search).or().like(Resume::getExperience,search);

        }
        return resumeMapper.selectPage(page,wrapper);
    }

    /**
     * 发送面试邀请
     * @param id
     */
    @Override
    public void sendInterviewInvitation(Integer id) {
        // 先查询简历
        Resume resume = resumeMapper.selectOne(new QueryWrapper<Resume>().eq("id", id));
        if (resume!= null) {
            // 先判断是否已邀请，避免空指针
            if (resume.getIsInvited() == 0) {
                // 创建一个新的对象，只更新需要修改的字段
                Resume updateResume = new Resume();
                updateResume.setUserId(resume.getUserId());
                updateResume.setIsInvited(1);
                updateResume.setIsApproved(1);
                resumeMapper.update(updateResume, new QueryWrapper<Resume>().eq("user_id", resume.getUserId()));
                // 发送邮件
                SimpleMailMessage message = new SimpleMailMessage();
                // 先检查 email 是否不为空
                if (resume.getEmail()!= null) {
                    message.setFrom(username);
                    message.setTo(resume.getEmail());
                    log.info("resume.getEmail(): {}", resume.getEmail());
                    message.setSubject("面试邀请");
                    message.setText("尊敬的 " + resume.getName() + "，您的简历已通过初审，我们诚挚地邀请您参加面试，请准时到达。");

                    try {
                        javaMailSender.send(message);
                        log.info("邮件发送成功，收件人: {}", resume.getEmail());
                    } catch (Exception e) {
                        log.error("邮件发送失败，收件人: {}, 错误: {}", resume.getEmail(), e.getMessage());
                    }
                } else {
                    log.error("用户 {} 的简历中 email 字段为空，无法发送面试邀请。", id);
                }
            } else {
                log.info("用户 {} 的简历已发送过面试邀请，不再重复发送。", id);
            }
        } else {
            log.error("未找到用户 {} 的简历，无法发送面试邀请。", id);
        }

    }

    /**
     * 拒绝简历
     * @param id
     */
    @Override
    public void rejectResume(Integer id) {
        Resume resume= resumeMapper.selectOne(new QueryWrapper<Resume>().eq("id", id));
        if (resume!= null) {
            // 先判断是否已邀请，避免空指针
            if (resume.getIsInvited() == 0) {
                // 创建一个新的对象，只更新需要修改的字段
                Resume updateResume = new Resume();
                updateResume.setUserId(resume.getUserId());
                updateResume.setIsApproved(2);
                resumeMapper.update(updateResume, new QueryWrapper<Resume>().eq("user_id", resume.getUserId()));
                // 发送邮件
                SimpleMailMessage message = new SimpleMailMessage();
                // 先检查 email 是否不为空
                if (resume.getEmail()!= null) {
                    message.setFrom(username);
                    message.setTo(resume.getEmail());
                    log.info("resume.getEmail(): {}", resume.getEmail());
                    message.setSubject("面试邀请");
                    message.setText("尊敬的 " + resume.getName() + "您好！，您的简历没有通过初审。");

                    try {
                        javaMailSender.send(message);
                        log.info("邮件发送成功，收件人: {}", resume.getEmail());
                    } catch (Exception e) {
                        log.error("邮件发送失败，收件人: {}, 错误: {}", resume.getEmail(), e.getMessage());
                    }
                } else {
                    log.error("用户 {} 的简历中 email 字段为空，无法发送面试邀请。", id);
                }
            } else {
                log.info("用户 {} 的简历已发送过面试邀请，不再重复发送。", id);
            }
        } else {
            log.error("未找到用户 {} 的简历，无法发送面试邀请。", id);
        }
    }

    /**
     * 统计待审核简历数量
     * @return
     */
    @Override
    public Long getPendResumeCount() {
        return resumeMapper.selectCount(new QueryWrapper<Resume>().eq("is_approved",0));
    }

}
